<?php
/**
 * ***********************************************************************************
 * 咨询鲤 PC端知识店铺-订单相关
 * 
 * @author Mr.RJH
 * @date 2025-09-09
 * @email<15213026209@163.com>
 * ***********************************************************************************
 */
namespace app\controller;

use think\facade\Db;
use dh2y\qrcode\QRcode;
use app\model\product\ZxlKnowStoreProductModel;
use app\model\product\ZxlKnowStoreProductAttrModel;

use app\model\order\ZxlKnowStoreOrderModel;

use app\model\user\ZxlKnowStoreAddressModel;

use app\service\KnowStoreApiService;

use app\BaseController;
class Order extends BaseController
{
    /**
     * 预下单页
     * 
     * @return mixed
     */
    public function prepare()
    {
        $id = $this->request->param('id');
        $attr_id = $this->request->param('attr_id', 0);
        $num = $this->request->param('num', 1);
        if (!$num || $num < 0) {
            $num = 1;
        }
        $info = ZxlKnowStoreProductModel::where(['m_id' => $this->request->m_id, 'id' => $id, 'is_delete' => 0])->find();
        if (!$info) {
            return redirect('/error/http404');
        }
        $info['num'] = $num;
        if ($info['product_type'] == 10) {
            $attr = ZxlKnowStoreProductAttrModel::where('product_id', $info['id'])->find();
            $info['head_imgs'] = '/static/images/exam.png';
        } else {
            $attr = ZxlKnowStoreProductAttrModel::where(['id' => $attr_id, 'product_id' => $info['id']])->find();
            $info['head_imgs'] = $info['head_imgs'] ? explode(',',$info['head_imgs'])[0] : '/static/images/no_pic_1.png';
        }
        $info['attr'] = $attr;

        $info['href'] = ZxlKnowStoreProductModel::getPcProductDetailHref($info['product_type'], $info['id']);
        $info['product_type_text'] = ZxlKnowStoreProductModel::getPcProductType($info['product_type']);
        
        // 获取收货地址
        $address_list = ZxlKnowStoreAddressModel::where(['m_id' => $this->request->m_id, 'user_id' => $this->user_id])->order(['default' => 'asc', 'id' => 'desc'])->select()->toArray();

        // 价格计算
        $knowStoreApiService = new KnowStoreApiService($this->request->m_id, $this->user_token);
        $price = $knowStoreApiService->calcPrice($attr_id, $id, $info['num']);
        
        $this->assign('info', $info);
        $this->assign('price', $price);
        $this->assign('address_list', $address_list);
        return $this->fetch();
    }

    /**
     * 价格计算
     * 
     * @return array
     */
    public function get_calc_price()
    {
        if ($this->request->isPost()) {
            $product_id = $this->request->param('product_id');
            $attr_id = $this->request->param('attr_id', 0);
            $goods_num = $this->request->param('num', 1);
            $coupon_id = $this->request->param('coupon_id', 0);
            $address_id = $this->request->param('address_id', 0);
            // 价格计算
            $knowStoreApiService = new KnowStoreApiService($this->request->m_id, $this->user_token);
            $result = $knowStoreApiService->calcPrice($attr_id, $product_id, $goods_num, $coupon_id, $address_id);

            return json(['code' => 0, 'msg' => 'SUCCESS', 'data' => $result]);
        }
    }

    /**
     * 创建订单
     * 
     * @return json
     */
    public function create()
    {
        if ($this->request->isPost()) {
            Db::startTrans();

            $knowStoreApiService = new KnowStoreApiService($this->request->m_id, $this->user_token);
            try {
                $post = $this->request->post();
                $result = $knowStoreApiService->orderCreate($post);
                if (isset($result['payment']['code_url'])) {
                    $code = new QRcode();
                    $size = 6; // 二维码大小
                    
                    $code_url = $result['payment']['code_url'];
                    $qrcode_url = $code->png($code_url, false, $size)->entry();
                } else {
                    Db::rollback();
                    return json(['code' => 1,'msg' => '请求支付失败，请刷新页面重试']);
                }
                $data['qrcode_url'] = $qrcode_url;
                $data['order_id'] = $result['order_id'];
                Db::commit();
                return json(['code' => 0,'msg' => 'SUCCESS', 'data' => $data]);
            } catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 1,'msg' => $e->getMessage()]);
            }
        }
    }

    /**
     * 继续支付
     * 
     * @return mixed
     */
    public function continue_pay()
    {
        if ($this->request->isPost()) {
            Db::startTrans();

            $knowStoreApiService = new KnowStoreApiService($this->request->m_id, $this->user_token);
            try {
                $post = $this->request->post();
                $result = $knowStoreApiService->payAgainOrder($post);
                
                if (isset($result['payment']['code_url'])) {
                    $code = new QRcode();
                    $size = 6; // 二维码大小
                    
                    $code_url = $result['payment']['code_url'];
                    $qrcode_url = $code->png($code_url, false, $size)->entry();
                } else {
                    Db::rollback();
                    return json(['code' => 1,'msg' => '请求支付失败，请刷新页面重试']);
                }
                $data['qrcode_url'] = $qrcode_url;
                $data['order_id'] = $result['order_id'];
                Db::commit();
                return json(['code' => 0,'msg' => 'SUCCESS', 'data' => $data]);
            } catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 1,'msg' => $e->getMessage()]);
            }
        }
        $order_id = $this->request->param('order_id');

        $info = ZxlKnowStoreOrderModel::with("orderGoods")->where(['id' => $order_id,'user_id'=>$this->user_id,'m_id'=>$this->request->m_id])->find();
        foreach ($info['orderGoods'] as &$v) {
            $product = ZxlKnowStoreProductModel::where('id', $v['product_id'])->find();
            $v['product_type'] = $product['product_type'];
            $v['background_color'] = $product['background_color'];
            $v['sub_title'] = $product['sub_title'];
            $v['product_type_text'] = ZxlKnowStoreProductModel::getPcProductType($product['product_type']);
        }
        
        $this->assign('info', $info);
        return $this->fetch();
    }

    /**
     * 检查订单是否支付
     * 
     * @return json
     */
    public function check_order_pay()
    {
        if ($this->request->isPost()) {
            try {
                $order_id = $this->request->param('order_id');
                $order = ZxlKnowStoreOrderModel::where(['id' => $order_id,'user_id'=>$this->user_id,'m_id'=>$this->request->m_id])->find();
                if ($order['status'] == 1) {
                    return json(['code' => 0,'msg' => '支付成功']);
                }
                return json(['code' => 1,'msg' => '你还未完成支付，请先完成支付']);
            } catch (\Exception $e) {
                return json(['code' => 1,'msg' => $e->getMessage()]);
            }
        }
    }
    
    /**
     * 免费领取课程
     * 
     * @return json
     */
    public function get_free_power()
    {
        if ($this->request->isPost()) {
            Db::startTrans();

            $knowStoreApiService = new KnowStoreApiService($this->request->m_id, $this->user_token);
            try {
                $post = $this->request->post();
                $result = $knowStoreApiService->getFreePower($post['product_id']);
                
                Db::commit();
                return json(['code' => 0,'msg' => '领取成功']);
            } catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 1,'msg' => $e->getMessage()]);
            }
        }
    }
}